package preCache

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/robfig/cron/v3"
	log "github.com/sirupsen/logrus"
	"user-center/src/db"
	"user-center/src/model"
	"user-center/src/utils"
)

// 每天执行，预热推荐用户
func doCacheRecommendUser() {
	key := "redis:dying:preCache:lock"
	lock := utils.NewRedisLock(db.RedisClient, context.Background(), key, utils.DefaultExpireTime)
	success, err := lock.Lock()
	if !success  || err != nil {
		return
	}
	defer lock.UnLock()
	//todo 设计分布式信号量
	for i := 0; i < 20; i++ {
		recommend(i + 1)
	}
}

func recommend(pageNum int) {
	pageSize := 20

	var userPageData string
	redisKey := fmt.Sprintf("parener:user:recommend:pageNum:%d:pageSize:%d", pageNum , 20)

	var userPage []model.User
	if err := db.GetMySQL().Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&userPage).Error; err != nil {
		log.Errorf("get recommend user error %v", err.Error())
		return
	}
	var safetyUserList []model.User
	for _, v := range userPage {
		safetyUser := utils.GetSafetyUser(&v)
		safetyUserList = append(safetyUserList, safetyUser)
	}
	userPageJson, err := json.Marshal(safetyUserList)
	if err != nil {
		log.Errorf("json convert error %v", err.Error())
		return
	}
	userPageData = string(userPageJson)
	// 永不过期
	db.RedisClient.Set(context.Background(), redisKey, userPageData, 0)
	log.Info("preCache starting...")
}
func InitCron() {
	c := cron.New()
	// 添加一个每天凌晨3点执行的任务
	//field name   | Mandatory? | Allowed values  | Allowed special characters
	//----------   | ---------- | --------------  | --------------------------
	//Minutes      | Yes        | 0-59            | * / , -
	//Hours        | Yes        | 0-23            | * / , -
	//Day of month | Yes        | 1-31            | * / , - ?
	//Month        | Yes        | 1-12 or JAN-DEC | * / , -
	//Day of week  | Yes        | 0-6 or SUN-SAT  | * / , - ?
	_, err := c.AddFunc("39 1 * * *", func() {
		// 这里执行你的删除操作
		doCacheRecommendUser()
	})
	if err != nil {
		log.Errorf("Add task error,  message: %v", err)
	}
	log.Info("start cron preCache")
	c.Start()
}
